package com.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.store.entity.Address;
import com.store.mapper.AddressMapper;
import com.store.mapper.DictDistrictMapper;
import com.store.service.IAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.store.service.ex.AddMaxException;
import com.store.service.ex.InsertException;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cai
 * @since 2022-07-12
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {
    @Autowired
    private AddressMapper addressMapper;


    @Autowired
    private DictDistrictMapper districtMapper;      //补全一下地址信息没别的用

    @Override
    public void addAddress(int uid,String username,Address address) {
        List<Address> result=addressMapper.selectByUid(uid);
        if(result.size()>=20){
            throw new AddMaxException("已经达到地址最大数量20限制！");
        }
        //补全地址信息 省、市、区
        address.setProvinceName(districtMapper.selectByCode(address.getProvinceCode()));
        address.setCityName(districtMapper.selectByCode(address.getCityCode()));
        address.setAreaName(districtMapper.selectByCode(address.getAreaCode()));
        //补全对象uid，时间相关，操作者
        address.setUid(uid);
        address.setCreatedTime(LocalDateTime.now());
        address.setCreatedUser(username);
        address.setModifiedTime(LocalDateTime.now());
        address.setModifiedUser(username);
        //添加到数据库
        Integer rows= addressMapper.insert(address);
        if(rows !=1 ){
            throw new InsertException("地址添加异常");
        }
    }

    @Override
    public List<Address> selectAllAddress(int uid) {
        return addressMapper.selectByUid(uid);
    }

    @Override
    public Void setDefault(int aid, int uid) {
        //先全部置非默认
        addressMapper.NoDefault(uid);
        //设置默认
        Address address=new Address();
        address.setAid(aid);
        address.setIsDefault(1);
        addressMapper.updateById(address);

        return null;
    }

    @Override
    public Void deleteAddress(int aid, int uid) {
        addressMapper.deleteByAid(aid,uid);
        return null;
    }
}
